package se.gala.core;

import java.text.DecimalFormat;
import java.util.Comparator;
import java.util.Map.Entry;
import java.util.TreeMap;
import java.util.Vector;

import se.gala.core.abstracts.Wagerable;
import se.gala.utils.Coordinate2D;
import se.gala.utils.GGObject;

public final class M3GMove extends GGObject {
	final public Coordinate2D loc1;
	final public Coordinate2D loc2;
	private Vector<Wagerable> wins;
	private static TreeMap<Wagerable, Integer> records;
	private static Integer totalRecords;
	private final static DecimalFormat DF = new DecimalFormat("#000.00");
	
	public M3GMove(Coordinate2D loc1, Coordinate2D loc2) {
		/* Ensure that loc1 and loc2 of same values are always stored in the same order */
		if (loc1.compareTo(loc2) <= 0) {
			this.loc1 = loc1;
			this.loc2 = loc2;
		} else {
			this.loc1 = loc2;
			this.loc2 = loc1;
		}
	}
	
	public void setWins(Vector<Wagerable> wins) {
		this.wins = wins;
	}
	
	protected Vector<Wagerable> getWins() {
		return wins;
	}
	
	public int calculateWins(FixedOddsBet bet) {
		int winning = 0;
		for (Wagerable stake : wins) {
			bet.changeStakeType(stake);
			winning += bet.calculateWinningAmount();
		}
		doRecordStakes();
		return winning;
	}
	
	private void doRecordStakes() {
		if (records == null) {
			/* Assume that if it's not initialised then it's not needed to store records */
			return;
		}
		for (Wagerable stake : wins) {
			records.put(stake, 1 + records.get(stake));
			totalRecords++;
		}
	}
	
	public static String provideDumpRecords() {
		String dump = "Stake           \tPerMil\tCount";
		if (records != null) {
			for (Entry<Wagerable, Integer> entry : records.entrySet()) {
				dump += "\n" + entry.getKey() + "\t"
						+ DF.format((float) entry.getValue() * 1000 / totalRecords)
						+ "\t" + entry.getValue();
			}
		}
		return dump;
	}

	public static void initDumpRecords(Wagerable[] stakes) {
		if (records != null) {
			return;
		}
		totalRecords = 0;
		records = new TreeMap<Wagerable, Integer>(new QSKeysComp());
		
		for (Wagerable w : stakes) {
			records.put(w, 0);
		}
	}
}
class QSKeysComp implements Comparator<Wagerable>{
	 
    @Override
    final public int compare(Wagerable qs1, Wagerable qs2) {
        return qs1.toString().compareTo(qs2.toString());
    }
}